package com.fhnew.app.util;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

/**
 * Created by Administrator on 2017/8/16.
 * RecyclerView滚动到底部监听器
 */

public abstract class OnEndLessScrollListener extends RecyclerView.OnScrollListener {
    private boolean hasMore = true;
    private LinearLayoutManager mLinearLayoutManager;//声明一个LinearLayoutManager
    private int currentPage = 0;//当前页，从0开始
    private int totalItemCount; //已经加载出来的Item的数量
    private int previousTotal = 0;//主要用来存储上一个totalItemCount
    private int visibleItemCount;//在屏幕上可见的item数量
    private int firstVisibleItem;//在屏幕可见的Item中的第一个
    private int lastVisibleItemPosition;//在屏幕可见的Item中的最后一个
    private boolean loading = true;//是否正在上拉数据

    protected OnEndLessScrollListener(LinearLayoutManager linearLayoutManager) {
        this.mLinearLayoutManager = linearLayoutManager;
    }

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);

        visibleItemCount = recyclerView.getChildCount();
        totalItemCount = mLinearLayoutManager.getItemCount();
        firstVisibleItem = mLinearLayoutManager.findFirstVisibleItemPosition();
        lastVisibleItemPosition = mLinearLayoutManager.findLastVisibleItemPosition();

//        SYSOUtils.sOut(totalItemCount, previousTotal);
        if (loading) {
            if (totalItemCount > previousTotal) {
                //数据已经加载结束
                loading = false;
                previousTotal = totalItemCount;
            }
        }

        if (hasMore
                && !loading
                && totalItemCount - visibleItemCount <= firstVisibleItem
                && lastVisibleItemPosition == totalItemCount - 1) {
            currentPage++;
            SYSOUtils.sOut("加载更多",
                    "totalItemCount==" + totalItemCount,
                    "visibleItemCount==" + visibleItemCount,
                    "firstVisibleItem==" + firstVisibleItem,
                    "lastVisibleItemPosition==" + lastVisibleItemPosition);
            getMoreData(currentPage);
            loading = true;
        }
    }

    /**
     * 刷新RecyclerView时重置参数
     */
    public void reset() {
        currentPage
                = totalItemCount
                = previousTotal
                = visibleItemCount
                = firstVisibleItem
                = lastVisibleItemPosition
                = 0;
        loading = hasMore = true;
    }

    /**
     * 无更多信息加载
     */
    public void setNoMore() {
        hasMore = false;
    }

    /**
     * 加载更多信息
     *
     * @param currentPage 页码
     */
    public abstract void getMoreData(int currentPage);
}
